// pages/home/home.js
import {
  getMultiData,
  getProductData
} from "../../service/home";

import * as Constant from "../../common/constant";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    banner: [],
    recommend: [],
    tabTitles: [{
        type: Constant.POP,
        title: '流行'
      },
      {
        type: Constant.NEW,
        title: '新款'
      },
      {
        type: Constant.SELL,
        title: '精选'
      }
    ],
    currentType: Constant.POP,
    currentPage: 0,
    goodsList: [],
    detailUrl: '/pages/detail/detail',
    showBackToTop: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getMultiData().then(res => {
      this.setData({
        banner: res.data.banner.list.map(value => value.image),
        recommend: res.data.recommend.list
      })
    });
    this._productData(Constant.POP);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this._productData(this.data.currentType);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 监听用户滑动页面事件
   */
  onPageScroll: function (options) {
    let backToTopFlag = options.scrollTop > Constant.showBackToTopDistance;
    if (backToTopFlag !== this.data.showBackToTop) {
      this.setData({
        showBackToTop: backToTopFlag
      })
    }
  },
  _productData(currentType) {
    let currentPage = 0;
    let goodsList = [];
    if (this.data.currentType === currentType) {
      currentPage = this.data.currentPage;
      goodsList = this.data.goodsList;
    }
    currentPage += 1;
    getProductData(currentType, currentPage).then(res => {
      goodsList.push(...res.data.list);
      this.setData({
        currentType,
        currentPage,
        goodsList
      })
    });
  },
  tabControlItemClick(event) {
    this._productData(event.detail.type);
    //跳转到tabControll组件位置
    wx.pageScrollTo({
      selector: '#tabControl'
    })
  },
  handleBackToTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  }
})